﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CommentItem : MonoBehaviour
{
    public UserInfoMoment userInfoMoment;
    public Text content;

    public Text likeNum;
    public Image likeImg;

    public Text timeText;

    Comment m_Data;
    public Comment data => m_Data;

    public UserMoment userMoment => GetComponentInParent<MomentPanel>().data;

    public void Init(Comment comment)
    {
        m_Data = comment;

        content.text = comment.content;
        userInfoMoment.Init(comment.miniUserInfo);

        RefreshLike(comment.likes);

        RefreshTime();
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }
    void RefreshTime()
    {
        this.timeText.text = UnityFunctions.GetTimeElapsed(data.time) + "前";
    }
    bool myLike;
    public void RefreshLike(List<long> likes)
    {
        if (likes != null)
        {
            likeNum.text = likes.Count.ToString();

            myLike = false;
            for (int i = 0; i < likes.Count; i++)
            {
                if (likes[i] == MGame.instance.MUser.id)
                {
                    myLike = true;
                    break;
                }
            }
            likeImg.gameObject.SetActive(myLike);
        }
        else
        {
            likeNum.text = "0";
            likeImg.gameObject.SetActive(false);
        }
    }

    public void OnClickLike()
    {
        RequestServerController.instance.ReqLikeComment(MGame.instance.MUser.id,!myLike, userMoment.userId, userMoment.moment.momentId,
            this.data.userId, this.m_Data.commentId, (res) =>
        {
            m_Data.AddLike(MGame.instance.MUser.id);

            RefreshLike(m_Data.likes);
        });
    }

    void Update()
    {
        if (Time.frameCount % 300 == 0)
        {
            RefreshTime();
        }
    }
}
